import React, { useState, useEffect } from 'react'
import { Card, Checkbox, Upload, Alert, Steps, Tabs, Form, Input, Button, Cascader, message  } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { getAllCate } from '../../../app/goodscate'
import { getParamsAPI } from '../../../app/params'
import { addGoodsAPI } from '../../../app/goods'
import { useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
// 引入编辑器组件
import BraftEditor from 'braft-editor'
  // 引入编辑器样式
import 'braft-editor/dist/index.css'
import './addgoods.less'
const { Step } = Steps
const { TabPane } = Tabs
const CheckboxGroup = Checkbox.Group
export default function AddGoods () {
    const token = useSelector(state => state.loginToken.token)
    const history = useHistory()
    // 获取商品信息的form表单实例
    const [goodsInfo] = Form.useForm()
    // 初始化商品分类数据
    const [allGoodsCate, setAllGoodsCate] = useState([])
    // 商品分类默认选中项
    const [defaultCate, setDefaultCate] = useState([])
    // 激活的进度条
    const [activeStep, setActiveStep] = useState(0)
    // 初始化动态参数
    const [dynamicParams, setDynamicParams] = useState([])
    // 初始化静态属性
    const [staticProps, setStaticProps] = useState([])
    // 初始化上传图片
    const [fileList, setFileList] = useState([])
    // 初始化富文本编辑器的内容
    const [editorState, setEditorState]= useState(BraftEditor.createEditorState(''))

    // 获取商品分类
    const getGoodsCate = async () => {
      const { data, meta } = await getAllCate()
      if(meta.status !== 200) return message.error('获取商品分类失败')
      setAllGoodsCate(data)
    }

    // 发请求， 获取商品参数和属性
    const getGoodsPropParam = async sel => {
      const { meta, data } = await getParamsAPI(defaultCate[2], sel)
        if(meta.status !== 200) return message.error(`获取商品${sel === 'many' ? '动态参数' : '静态属性'}失败`)
        data.forEach(item => item.attr_vals = item.attr_vals.trim() ? item.attr_vals.trim().split(' ') : [])
        sel === 'many' ? setDynamicParams(data) : setStaticProps(data)
    }
    // 监听分类参数是否改变
    useEffect(() => {
      setDynamicParams([])
      setStaticProps([])
    }, [defaultCate])

    // 级联选择框改变
    const  onCascaderChange = values => {
        if(values.length < 3) {
          setDefaultCate([])
          goodsInfo.setFieldsValue({goods_cat: []})
          return
        }
        // console.log(values);
        setDefaultCate(values)
      }

    // tabs 切换产生的事件处理
    const tabChangeCallBack = activeKey => {
      // console.log(activeKey)
      if(!defaultCate.length) return message.error('请先选择三级商品分类')
      setActiveStep(+activeKey)
      if(activeKey === '1' && !dynamicParams.length) {
        getGoodsPropParam('many')
      } else if (activeKey === '2' && !staticProps.length) {
        getGoodsPropParam('only')
      }
    }
    // 图片上传改变事件
    const picSuccessUpdate = ({ file: { response } }) => {
      if(!response) return
      const { data, meta } = response
      console.log(data)
      if(meta.status !== 200) return message.error('上传失败')
      setFileList( preList => {
        preList.push({pic: data.tmp_path})
        return preList
      })
    }
    // 商品动态参数改变
    const onChangeDynamicParams = (checkVal, attrId) => {
      setDynamicParams(preVal => {
        preVal.forEach(item => {
          if(item.attr_id === attrId) {
            item.attr_vals = checkVal
          }
        })
        return preVal
      })
    }
    // 商品静态属性改变
    const onChangeStaticProps = (checkVal, attrId) => {
      setStaticProps(preVal => {
        preVal.forEach(item => {
          if(item.attr_id === attrId) {
            item.attr_vals = checkVal
          }
        })
        return preVal
      })
    }
    // 富文本编辑器改变
    const handleEditorChange = (editorState) => {
      //读取富文本内容
      setEditorState(editorState.toHTML())
    }
    // 表单提交成功
    const onFinish = async values => {
      values.goods_cat = values.goods_cat.join(',')
      const handlerDynamic = dynamicParams.filter(item => item.attr_vals.length)
      .map(item => ({
        attr_id: item.attr_id,
        attr_value: item.attr_vals.join(',')
      }))
      const handlerStatic = staticProps.filter(item => item.attr_vals.length)
      .map(item => ({
        attr_id: item.attr_id,
        attr_value: item.attr_vals.join(',')
      }))
      Object.assign(values, {
        goods_introduce: editorState,
        pics: fileList,
        attrs: handlerDynamic.concat(handlerStatic)
      })
      // console.log(values)
      const { meta } = await addGoodsAPI(values)
      if(meta.status !== 201) return message.error('添加商品失败')
      history.push('/goods')
    }
  // 表单提交失败
  const onFinishFailed = (errorInfo) => {
      errorInfo?.errorFields.forEach(item => {
        item.errors.forEach(info => {
          message.error(info)
        })
      })
  }
    return (
        <Card className="add-goods">
            <Alert message="添加商品信息" type="info" showIcon />
            <Steps current={activeStep} >
                <Step title="基本信息" />
                <Step title="商品参数" />
                <Step title="商品属性" />
                <Step title="商品图片" />
                <Step title="商品内容" />
                <Step title="完成" className="last-step"/>
            </Steps>
            <Form
                name="addGoods"
                form={goodsInfo}
                labelCol={{span: 2}}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
                <Tabs
                    tabPosition="left"
                    onChange={tabChangeCallBack}
                    activeKey={activeStep + ''}
                >
                    <TabPane tab="基本信息" key="0">
                        <Form.Item
                            label="商品名称"
                            name="goods_name"
                            rules={[{ required: true, message: '商品名称不能为空' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="商品价格"
                            name="goods_price"
                            rules={[{ required: true, message: '商品价格不能为空' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="商品重量"
                            name="goods_weight"
                            rules={[{ required: true, message: '商品重量不能为空' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="商品数量"
                            name="goods_number"
                            rules={[{ required: true, message: '商品数量不能为空' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="商品分类"
                            name="goods_cat"
                            rules={[{ required: true, message: '商品分类不能为空' }]}
                        >
                            <Cascader
                                options={allGoodsCate}
                                expandTrigger="hover"
                                placeholder="请选择"
                                allowClear={false}
                                value={defaultCate}
                                className="goods-category"
                                notFoundContent="加载中..."
                                onChange={onCascaderChange}
                                onFocus={getGoodsCate}
                                fieldNames={{
                                  label:'cat_name',
                                  value:'cat_id'
                              }}
                            />
                        </Form.Item>
                    </TabPane>
                    <TabPane tab="商品参数" key="1">
                    {
                      dynamicParams.map(item => {
                        return <Form.Item
                            label={item.attr_name}
                            // name={item.attr_name}
                            key={item.attr_id}
                               >
                            {
                              item.attr_vals && <CheckboxGroup defaultValue={item.attr_vals} options={item.attr_vals} onChange={(e) => {onChangeDynamicParams(e, item.attr_id)}} />
                            }
                        </Form.Item>
                      })
                    }
                    </TabPane>
                    <TabPane tab="商品属性" key="2">
                    {
                      staticProps.map(item => {
                        return <Form.Item
                            label={item.attr_name}
                            key={item.attr_id}
                               >
                            {
                              item.attr_vals && <CheckboxGroup defaultValue={item.attr_vals} options={item.attr_vals} onChange={(e) => {onChangeStaticProps(e, item.attr_id)}} />
                            }
                        </Form.Item>
                      })
                    }
                    </TabPane>
                    <TabPane tab="商品图片" key="3">
                    <Upload
                        action="https://www.liulongbin.top:8888/api/private/v1/upload"
                        listType="picture"
                        onChange={picSuccessUpdate}
                        headers={{
                          Authorization: token
                        }}
                    >
                      <Button type="primary" icon={<UploadOutlined />}>点击上传</Button>
                    </Upload>
                    </TabPane>
                    <TabPane tab="商品内容" key="4">
                     {/* 富文本编辑器 */}
                    <Form.Item>
                      <BraftEditor
                          value={editorState}
                          // style={{height:'500px'}}
                          onChange={(e)=>{handleEditorChange(e)}}
                      />

                    </Form.Item>
                    {/* 表单提交 */}
                    <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                        提交
                        </Button>
                    </Form.Item>
                    </TabPane>
                </Tabs>
            </Form>
        </Card>
    )
}